package net.sf.rose.business.action.define;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import json.JsonHttpRequestBean;
import json.JsonHttpResponse;
import json.JsonTreeBean;
import net.sf.rose.business.action.Download;
import net.sf.rose.business.bean.base.DownloadFileBean;
import net.sf.rose.business.bean.database.FieldMetaBean;
import net.sf.rose.business.bean.database.TableMetaBean;
import net.sf.rose.business.service.DataBaseService;
import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.jdbc.DBUtils;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.util.ListProperty;
import net.sf.rose.web.OnlineUserListener;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;

/**
 * 功能：
 * 
 * @author fengjian
 * @since 2014/01/29
 */
@Controller
@RequestMapping("/define/database")
public class DataBaseController {

	private static String SQL_PAGE = "define/database/sql";

	/**
	 * 
	 */
	@RequestMapping("/list.html")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) {
		Map<String, TableMetaBean> bean = DataBaseService.getService().getAll();
		List<JsonTreeBean> list = new ArrayList<JsonTreeBean>();
		JsonTreeBean tree = new JsonTreeBean();
		tree.setId("all");
		tree.setName("所有表名称");
		tree.setExpanded(true);
		list.add(tree);
		for(TableMetaBean table : bean.values()){
			tree = new JsonTreeBean();
			tree.setPid("all");
			tree.setId(table.getName());
			tree.setName(table.getName()+'('+table.getText()+')');
			list.add(tree);
		}
		JsonHttpResponse.renderJson(response, list);
		return null;
	}

	/**
	 * 
	 */
	@RequestMapping("/get.html")
	public ModelAndView get(HttpServletRequest request, HttpServletResponse response, String name) {
		TableMetaBean bean = DataBaseService.getService().getTable(name);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", bean);
		JsonHttpResponse.renderJson(response, map);
		return null;
	}

	/**
	 * 
	 */
	@RequestMapping("/getTable.html")
	public ModelAndView getTable(HttpServletRequest request, HttpServletResponse response, String name) {
		TableMetaBean bean = DataBaseService.getService().getTable(name);
		//Map<String, Object> map = new HashMap<String, Object>();
		//map.put("data", bean.getFields());
		JSONSerializer serializer = new JSONSerializer();
		serializer.exclude("UID");
		serializer.transform(new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"), Date.class);
		serializer.transform(new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"), Timestamp.class);
		//serializer.deepSerialize(bean);
		JsonHttpResponse.renderJson(response, serializer.deepSerialize(bean));
		return null;
	}

	/**
	 * 保存数据库字段操作
	 */
	@RequestMapping("/save.html")
	public void save(HttpServletRequest request, HttpServletResponse response, String data) {
		JsonHttpRequestBean json = new JsonHttpRequestBean(data);
		json.parseJson(FieldMetaBean.class);
		String tableName = json.getParamemter("tableName");
		TableMetaBean table = DataBaseService.getService().getTable(tableName);
		table.setText(json.getParamemter("text"));
		table.setDescription(json.getParamemter("description"));
		table.setKeyGenerate(json.getParamemter("keyGenerate"));
		int type = 0;
		for (int i = 0; i < json.size(); i++) {
			type = json.getAction(i);
			if (type == DBUtils.TYPE_INSERT_INT) {
				table.addField((FieldMetaBean) json.getBean(i));
			} else if (type == DBUtils.TYPE_UPDATE_INT) {
				table.updateField((FieldMetaBean) json.getBean(i));
			} else if (type == DBUtils.TYPE_DELETE_INT) {
				table.removeField((FieldMetaBean) json.getBean(i));
			}
		}
		JSONSerializer serializer = new JSONSerializer();
		serializer.exclude("UID");
		serializer.transform(new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"), Date.class);
		serializer.transform(new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"), Timestamp.class);
		JsonHttpResponse.renderJson(response, serializer.deepSerialize(table));
		//JsonHttpResponse.renderJson(response, table);
	}

	/**
	 * 添加数据库的表
	 */
	@RequestMapping("/addTable.html")
	public void addTable(HttpServletRequest request, HttpServletResponse response, String name) {
		if (name == null) {
			return;
		}
		TableMetaBean bean = new TableMetaBean();
		bean.setName(name);
		DataBaseService.getService().getAll().put(name, bean);
		JsonHttpResponse.renderMessage(response, "ok");
	}
	
	/**
	 * 删除数据库的表定义
	 */
	@RequestMapping("/deleteTable.html")
	public void deleteTable(HttpServletRequest request, HttpServletResponse response, String name) {
		DataBaseService.getService().getAll().remove(name);
		JsonHttpResponse.renderMessage(response, "ok");
	}

	/**
	 * 保存数据库表定义
	 */
	@RequestMapping("/saveAll.html")
	public void saveAll(HttpServletRequest request, HttpServletResponse response) {
		UserBean user = OnlineUserListener.getOnlineUser(request);
		if (user == null) {
			user = new UserBean();
			user.setUserName("system");
		}
		DataBaseService.save(user);
		JsonHttpResponse.renderMessage(response, "保存成功！");
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/createSql.html")
	public ModelAndView createSql(HttpServletRequest request) {
		DataBaseService.getService().createDatabaseUpdateSql();
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/getSql.html")
	public ModelAndView getSql(HttpServletRequest request) {
		List<String> list = DataBaseService.getService().getDatabaseUpdateSql();
		ModelAndView mav = new ModelAndView(SQL_PAGE);
		mav.addObject("bean", list);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/execute.html")
	public ModelAndView execute(HttpServletRequest request) {
		UserBean user = OnlineUserListener.getOnlineUser(request);
		DataBaseService.getService().executeDatabaseUpdateSql(user);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/datasource.html")
	public ModelAndView datasource(HttpServletRequest request) {
		String properties = request.getParameter("properties").trim();
		if (properties != null && properties.length() > 0) {
			ListProperty pro = new ListProperty();
			for (String str : StringUtils.split(properties, "\r\n")) {
				if (str.indexOf(0) == '#') {
					pro.addComment(str);
				} else {
					String[] arr = StringUtils.split(str, '=');
					if (arr.length == 2) {
						pro.set(arr[0], arr[1]);
					}
				}
			}
			// DataBaseFactory.saveProperties(pro);
		}
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/input.html")
	public ModelAndView input(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(Download.TEMP_FILES);
		if (obj == null) {
			throw new SystemException("Session中找不到上传的文件。", SystemErrorCode.A_PRARAMTER_LOST_ERROR);
		}
		Map<String, DownloadFileBean> map = (Map<String, DownloadFileBean>) obj;
		InputStream in = null;
		try {
			for (DownloadFileBean bean : map.values()) {
				if (bean.getData() != null) {
					in = bean.getData().getInputStream();
					break;
				}
			}
		} catch (IOException e) {
			throw new SystemException("上传的文件读取错误 !", SystemErrorCode.A_PRARAMTER_LOST_ERROR);
		}
		if (in == null) {
			throw new SystemException("没有找到上传的文件 !", SystemErrorCode.A_PRARAMTER_LOST_ERROR);
		}
		DataBaseService.input(in);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "导入成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/output.html")
	public String output(HttpServletRequest request) {
		File file = DataBaseService.output();
		request.setAttribute(Download.DOWNLOAD_FILE, file);
		request.setAttribute(Download.DOWNLOAD_FILE_NAME, "数据库配置.xml");
		return "forward:/download.html";
	}
}
